import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { PmpSysUserEntity } from '@/pmp/entity/pmp.sys.user.entity';
import { ILike, Repository } from 'typeorm';
import { UserPlusDto } from '@/pmp/dto/user/user.plus.dto';
import config from '../../../../../config';
import { ResultError, ResultMsg, ResultSuccess } from '@/utils/result';
import { UserQueryDto } from '@/pmp/dto/user/user.query.dto';
import { PageDto } from '@/pmp/dto/page.dto';
import { DeleteDto } from '@/pmp/dto/delete.dto';
import * as XLSX from 'xlsx';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(PmpSysUserEntity)
    private readonly userRepository: Repository<PmpSysUserEntity>,
  ) {}

  /**
   * 添加
   */
  async plus(data: UserPlusDto) {
    try {
      // 手机号和用户账号唯一
      const userName = await this.userRepository.find({
        where: {
          user_name: data.userName,
        },
      });
      if (userName.length > 0) {
        return {
          code: 201,
          msg: 'success',
          data: '当前用户已存在',
        };
      }
      const phone = await this.userRepository.find({
        where: {
          phone: data.phone,
        },
      });
      if (phone.length > 0) {
        return {
          code: 201,
          msg: 'success',
          data: '当前手机号已存在',
        };
      }

      await this.userRepository.save({
        user_name: data.userName,
        pass_word: config.DEFAULT,
        phone: data.phone,
        nick_name: data.nickName,
        sex: data.sex,
        email: data.email,
        status: data.status,
        avatar: data.avatar,
      });

      return {
        code: 200,
        msg: 'success',
        data: '添加成功',
      };
    } catch (e) {
      return ResultError();
    }
  }

  /**
   * 删除
   */
  async delete(data: DeleteDto) {
    try {
      const { id } = data;
      await this.userRepository.delete(id);
      return ResultMsg('删除成功');
    } catch (e) {
      ResultError();
    }
  }

  /**
   * 修改
   */
  async update(data) {}

  /**
   * 查询
   */
  async pageList(query: PageDto<UserQueryDto>) {
    try {
      const {
        page = 1,
        pageSize = 10,
        data: { nick_name, phone, user_name, sex, status, email },
      } = query;

      const where = {};
      if (nick_name) {
        Object.assign(where, { nick_name: ILike(`%${nick_name}%`) });
      }
      if (phone) {
        Object.assign(where, { phone });
      }
      if (user_name) {
        Object.assign(where, { user_name });
      }
      if (sex !== undefined) {
        // 0 男 1 女 2全部
        if (sex.toString() !== '2') {
          Object.assign(where, { sex });
        }
      }
      if (status !== undefined) {
        // 0 正常 1 禁用 2全部
        if (status.toString() !== '2') {
          Object.assign(where, { status });
        }
      }
      if (email) {
        Object.assign(where, { email });
      }

      const [list, total] = await this.userRepository.findAndCount({
        where,
        skip: (page - 1) * pageSize, // 偏移量
        take: pageSize,
        order: { create_time: 'DESC' },
        select: [
          'sex',
          'status',
          'nick_name',
          'phone',
          'user_name',
          'avatar',
          'email',
          'create_time',
          'id',
        ],
      });
      console.log(list);

      return ResultSuccess({
        page: page,
        pageSize: pageSize,
        total: total,
        list: list,
      });
    } catch (e) {
      ResultError();
    }
  }

  /**
   * 导入
   */
  async export(file: Express.Multer.File) {
    try {
      const workbook = XLSX.read(file.buffer, { type: 'buffer' });

      const sheet = workbook.Sheets[workbook.SheetNames[0]];

      const data = XLSX.utils.sheet_to_json(sheet);

      const users = data.map((row: any) => {
        return {
          // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
          user_name: row['账号'],
          // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
          phone: row['手机号'],
          // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
          nick_name: row['昵称'],
          // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
          sex: row['性别'] === '男' ? 0 : 1, // 性别处理为系统存储格式
          // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
          email: row['邮箱'],
          status: 1,
        };
      });

      for (const user of users) {
        // 检查重复
        const exists = await this.userRepository.findOne({
          // where: [{ user_name: user.user_name }, { phone: user.phone }],
          where: [
            {
              user_name: user.user_name as string,
            },
            {
              phone: user.phone as string,
            },
          ],
        });
        if (exists) {
          return ResultError(
            `用户 ${user.user_name} 或手机号 ${user.phone} 已存在`,
          );
        }

        // 保存到数据库
        await this.userRepository.save(user);
      }
      return ResultMsg('导入成功');
    } catch (e) {
      ResultError();
    }
  }
  // 下载用户导入模板
  generateTemplate() {
    // 表头
    const headers = ['账号', '手机号', '昵称', '性别', '邮箱'];
    // 示例
    const exampleData = [
      {
        账号: 'Alice', // 用户名示例
        手机号: '12345678901', // 手机号示例
        昵称: 'Alice123', // 昵称示例
        性别: '男', // 性别示例 (0: 男, 1: 女)
        邮箱: 'alice@example.com', // 邮箱示例
      },
      {
        账号: 'Alice', // 用户名示例
        手机号: '12345678901', // 手机号示例
        昵称: 'Alice123', // 昵称示例
        性别: '女', // 性别示例 (0: 男, 1: 女)
        邮箱: 'alice@example.com', // 邮箱示例
      },
    ];
    // 转换excel表头
    const worksheet = XLSX.utils.json_to_sheet(exampleData, {
      header: headers,
    });

    // 创建工作簿
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

    // eslint-disable-next-line @typescript-eslint/no-unsafe-return
    return XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
  }
}
